#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    vector<vector<int>> fourSum(vector<int> &nums, int target)
    {
        sort(nums.begin(), nums.end());
        int length = nums.size();
        vector<vector<int>> res;
        for (int i = 0; i < length; i++)
        {
            if (nums[i] > target && nums[i] >= 0)
            {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1])
            {
                continue;
            }
            for (int j = i + 1; j < length; j++)
            {
                int sum = nums[i] + nums[j];
                if (sum > target && sum >= 0)
                {
                    break;
                }
                if (j > i + 1 && nums[j] == nums[j - 1])
                {
                    continue;
                }
                int left = j + 1;
                int right = length - 1;
                while (left < right)
                {
                    long long flag = (long long)sum + (long long)nums[left] + (long long)nums[right];
                    if (flag > target)
                    {
                        right--;
                    }
                    else if (flag < target)
                    {
                        left++;
                    }
                    else
                    {
                        res.push_back({nums[i], nums[j], nums[left], nums[right]});
                        while (left < right && nums[left] == nums[left + 1])
                        {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right - 1])
                        {
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }
        }
        return res;
    }
};

int main()
{
    vector<int> vec{1, -2, -5, -4, -3, 3, 3, 5};
    Solution sol;
    vector<vector<int>> res = sol.fourSum(vec, -11);
    for (auto vec : res)
    {
        for (auto num : vec)
        {
            cout << num << " ";
        }
        cout << endl;
    }
    return 0;
}